package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.PaginationData;
import com.chagee.base.utils.PaginationRequest;
import com.chagee.lark.anno.ExceptionLarkNotice;
import com.chagee.lark.enums.UrgentTypeEnum;
import com.chagee.payment.sdk.dto.request.SendNotifyReq;
import com.chagee.payment.sdk.utils.NotifyCommonHandler;
import com.chagee.store.operation.api.bo.*;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.api.request.*;
import com.chagee.store.operation.api.response.SettlementResponse;
import com.chagee.store.operation.api.response.WorkOrderResponse;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.StoreConfigurationMapper;
import com.chagee.store.operation.server.event.dao.StoreDetailMapper;
import com.chagee.store.operation.server.event.dao.StoreSettlementMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.service.StoreConfigurationBaseService;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.chagee.store.operation.server.model.bo.OrderPenalizeBO;
import com.chagee.store.operation.server.model.bo.StoreDetailBO;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.third.*;
import com.chagee.store.operation.server.transfer.WorkOrderTransfer;
import com.chagee.store.operation.server.utils.DateUtil;
import com.chagee.storeManagement.api.event.enums.*;
import com.chagee.storeManagement.api.event.request.TimerEventRegisterDefaultRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 打烊结算
 * @Author : hk
 * @Date : 2024/10/14
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class StoreAppSettlementBizService {

	@Value("${payment.publicKey}")
	private String publicKey;
	@Value("${payment.privateKey}")
	private String privateKey;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private StoreDetailMapper storeDetailMapper;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private WorkOrderTransfer workOrderTransfer;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private StoreConfigurationMapper storeConfigurationMapper;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	@Resource
	private StoreSettlementMapper storeSettlementMapper;

	@Resource
	private WorkOrderBizService workOrderBizService;

	@Resource
	private BladeUserService bladeUserService;

	@Resource
	private FeiShuSendService feiShuSendService;

	@Resource
	private StoreBaseService storeBaseService;

	@Value("${settlement.storeTag}")
	private String storeTag;

	@Resource
	private EventThirdService eventThirdService;

	@Value("${settlement.supplierVerifyTimeout:259200}")
	private Integer supplierVerifyTimeout;

	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;

	private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

	/**
	 * 结算单列表/查询
	 */
	public PaginationData<SettlementResponse> querySettlementPage(PaginationRequest<SettlementAppRequest> paginationRequest) {
		//获取当前登录人门店信息
		BladeUser user = bladeUserService.getUser();
		List<String> userStoreCodeList = bladeUserService.getUserStoreCodeList(user.getUserId());

		SettlementAppRequest request = paginationRequest.getQueryParameter();
		if (CollUtil.isEmpty(userStoreCodeList) || (StringUtils.isNotBlank(request.getStoreNo()) && !userStoreCodeList.contains(request.getStoreNo()))) {
			return ResponseUtil.emptyResponse(paginationRequest, SettlementResponse.class, NumberUtils.LONG_ZERO);
		}

		if (StringUtils.isNotBlank(request.getStoreNo())) {
			userStoreCodeList = CollectionUtil.toList(request.getStoreNo());
		}

		Page<StoreSettlementDO> page = new Page<>(paginationRequest.getPageNum(), paginationRequest.getPageSize());

		LambdaQueryWrapper<StoreSettlementDO> wrapper = new LambdaQueryWrapper();
		wrapper.in(StoreSettlementDO::getStoreNo, userStoreCodeList);
		wrapper.eq(StoreSettlementDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		if (Objects.nonNull(request)) {
			if (StringUtils.isNotBlank(request.getDocumentStatus())) {
				wrapper.eq(StoreSettlementDO::getDocumentStatus, request.getDocumentStatus());
			}
			if (StringUtils.isNotBlank(request.getSettlementCycle())) {
				String startOfMonth = null;
				String endOfMonth = null;
				try {
					startOfMonth = DateUtil.getStartOfMonth(request.getSettlementCycle(), DateUtil.YEARS_DATE_PATTERN);
					endOfMonth = DateUtil.getEndOfMonth(request.getSettlementCycle(), DateUtil.YEARS_DATE_PATTERN);
				} catch (Exception e) {
					throw new BizException(BizErrorCode.DATE_CONVERT_FAIL);
				}
				wrapper.ge(StoreSettlementDO::getSettlementCycle, startOfMonth);
				wrapper.le(StoreSettlementDO::getSettlementCycle, endOfMonth);
			}
		}
		Page<StoreSettlementDO> settlementPage = storeSettlementBaseService.page(page, wrapper);

		if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
			return ResponseUtil.emptyResponse(paginationRequest, SettlementResponse.class, settlementPage.getTotal());
		}

//		Set<String> storeNoList = settlementPage.getRecords().stream().map(StoreSettlementDO::getStoreNo).collect(Collectors.toSet());
//
//		List<StoreDO> storeDOS = storeBaseService.batchSelectStoreList(storeNoList);
//		//加盟店 且门店标签包含"店长持股门店" 为true
//		Map<String, Boolean> hashMap = new HashMap<>();
//		for (StoreDO storeDO : storeDOS) {
//			if (StringUtils.equals(StoreCategoryEnum.JM.getType(), storeDO.getStoreCategory())) {
//				if (StringUtils.isNotBlank(storeDO.getTag())) {
//					TagJsonBO tagJsonBO = JSONObject.parseObject(storeDO.getTag(), TagJsonBO.class);
//					Set<String> tagCodes = tagJsonBO.getTagCodes();
//					if (tagCodes.contains(storeTag)) {
//						hashMap.put(storeDO.getStoreNo(), true);
//					} else {
//						hashMap.put(storeDO.getStoreNo(), false);
//					}
//				}
//			}
//		}
		List<SettlementResponse> list = converToTasktVO(settlementPage.getRecords());
		return ResponseUtil.commonResponse(paginationRequest, list, settlementPage.getTotal());
	}

	private List<SettlementResponse> converToTasktVO(List<StoreSettlementDO> dos) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		List<SettlementResponse> list = dos.stream().map(s -> {
			SettlementResponse settlementResponse = new SettlementResponse();
			BeanUtil.copyProperties(s, settlementResponse);
			settlementResponse.setSettlementCycle(sd.format(s.getSettlementCycle()));
//			if (Objects.nonNull(hashMap.get(s.getStoreNo()))) {
//				settlementResponse.setStoreTagFlag(hashMap.get(s.getStoreNo()));
//			}
			if (StringUtils.isNotBlank(s.getPenalizeMoney())) {
				OrderPenalizeBO orderPenalizeBO  = JSON.parseObject(s.getPenalizeMoney(), new TypeReference<OrderPenalizeBO>() {});
				settlementResponse.setCompletedOrderSize(String.valueOf(orderPenalizeBO.getCompletedOrderSize()));
				settlementResponse.setNotClosed(orderPenalizeBO.getNotClosed());
				settlementResponse.setOtherPenalizeSum(orderPenalizeBO.getOtherPenalizeSum());
				settlementResponse.setSettlementMoney(orderPenalizeBO.getPayMoney());
				settlementResponse.setFloorPrice(orderPenalizeBO.getFloorPrice());
			}
			return settlementResponse;
		}).collect(Collectors.toList());
		return list;
	}

	public SettlementResponse queryDetail(SettlementAppOrderDetailRequest request) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		if (Objects.isNull(request)) {
			throw new BizException(BizErrorCode.REQUEST_VALID_FAILED);
		}
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(request.getSettlementNo());
		SettlementResponse settlementResponse = new SettlementResponse();
		BeanUtil.copyProperties(storeSettlementDO, settlementResponse);

		settlementResponse.setSettlementCycle(sd.format(storeSettlementDO.getSettlementCycle()));

		InvoiceBO invoiceBO = new InvoiceBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getInvoice())) {
			invoiceBO  = JSON.parseObject(storeSettlementDO.getInvoice(), new TypeReference<InvoiceBO>() {});
		}
		settlementResponse.setInvoiceUrlList(invoiceBO.getInvoiceUrl());
		if (StringUtils.equals(StoreCategoryEnum.JM.getType(), storeSettlementDO.getStoreCategory())) {
			List<StoreDO> storeDOS = storeBaseService.batchSelectStoreList(Collections.singletonList(storeSettlementDO.getStoreNo()));
			if (CollectionUtil.isNotEmpty(storeDOS)) {
				StoreDO storeDO = storeDOS.stream().findFirst().get();

				Boolean tagFlag = Boolean.FALSE;
				if (StringUtils.isNotBlank(storeDO.getTag())) {
					TagJsonBO tagJsonBO = JSONObject.parseObject(storeDO.getTag(), TagJsonBO.class);
					Set<String> tagCodes = tagJsonBO.getTagCodes();
					if (tagCodes.contains(storeTag)) {
						tagFlag = true;
					}
				}
				settlementResponse.setStoreTagFlag(tagFlag);
			}
		}

		if (StringUtils.isNotBlank(storeSettlementDO.getPenalizeMoney())) {
			OrderPenalizeBO penalizeBO = JSON.parseObject(storeSettlementDO.getPenalizeMoney(), new TypeReference<OrderPenalizeBO>() {
			});
			settlementResponse.setCompletedOrderSize(String.valueOf(penalizeBO.getCompletedOrderSize()));
			settlementResponse.setNotClosed(penalizeBO.getNotClosed());
			settlementResponse.setOtherPenalizeSum(penalizeBO.getOtherPenalizeSum());
			settlementResponse.setSettlementMoney(penalizeBO.getPayMoney());
			settlementResponse.setFloorPrice(penalizeBO.getFloorPrice());
		}

		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			SettlementExtJsonBO settlementExtJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
			settlementResponse.setExtJsonBO(settlementExtJsonBO);
		}

		return settlementResponse;
	}

	public PaginationData<WorkOrderResponse> queryOrderList(PaginationRequest<SettlementAppOrderDetailRequest> request) {
		SettlementAppOrderDetailRequest queryParameter = request.getQueryParameter();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");


		PaginationRequest<WorkOrderRequest> workOrderRequest = new PaginationRequest<>();
		workOrderRequest.setPageSize(request.getPageSize());
		workOrderRequest.setPageNum(request.getPageNum());

		WorkOrderRequest orderRequest = new WorkOrderRequest();
		orderRequest.setStoreCode(queryParameter.getStoreCode());
		Date startOfMonth = null;
		Date endOfMonth = null;
		try {
			startOfMonth = getStartOfMonth(sd.parse(queryParameter.getSettlementCycle()));
			endOfMonth = getEndOfMonth(sd.parse(queryParameter.getSettlementCycle()));
		} catch (ParseException e) {
			throw new BizException(BizErrorCode.DATE_CONVERT_FAIL);
		}
		orderRequest.setCreateTimeStart(sdf.format(startOfMonth));
		orderRequest.setCreateTimeEnd(sdf.format(endOfMonth));
		orderRequest.setSupplierNo(queryParameter.getSupplierNo());
		workOrderRequest.setQueryParameter(orderRequest);
		return query(workOrderRequest);
	}

	public PaginationData<WorkOrderResponse> query(PaginationRequest<WorkOrderRequest> request){
		Page<WorkOrderDO> page = new Page<>(request.getPageNum(), request.getPageSize());

		WorkOrderRequest workOrderRequest = request.getQueryParameter();
		LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper();
		wrapper.notIn(WorkOrderDO::getDocumentStatus, Arrays.asList(StoreWorkOrderStatusEnum.EXPIRED.getType()));
		if(workOrderRequest!=null){
			if(workOrderRequest.getWorkOrderNumber()!=null){
				wrapper.like(WorkOrderDO::getWorkOrderNumber,workOrderRequest.getWorkOrderNumber());
			}
			if(workOrderRequest.getStoreCode()!=null){
				wrapper.eq(WorkOrderDO::getStoreCode,workOrderRequest.getStoreCode());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getStoreName())){
				wrapper.like(WorkOrderDO::getStoreName,workOrderRequest.getStoreName());
			}
			if(StringUtils.isNotBlank(workOrderRequest.getSupplierNo())){
				wrapper.eq(WorkOrderDO::getSupplierNo,workOrderRequest.getSupplierNo());
			}
			if(workOrderRequest.getReceiver()!=null){
				wrapper.like(WorkOrderDO::getReceiver,workOrderRequest.getReceiver()).or().like(WorkOrderDO::getReceiverMobile,workOrderRequest.getReceiver());
			}

			if(workOrderRequest.getSupplier()!=null){
				wrapper.like(WorkOrderDO::getSupplier,workOrderRequest.getSupplier());
			}
			if(workOrderRequest.getStoreCategory()!=null){
				wrapper.eq(WorkOrderDO::getStoreCategory,workOrderRequest.getStoreCategory());
			}
			if(workOrderRequest.getCreateTimeStart()!=null){
				wrapper.ge(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeStart());
			}
			if(workOrderRequest.getCreateTimeEnd()!=null){
				wrapper.le(WorkOrderDO::getCreateTime,workOrderRequest.getCreateTimeEnd());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getCompanyName()) ) {
				wrapper.eq(WorkOrderDO::getCompanyName, workOrderRequest.getCompanyName());
			}
			if (StringUtils.isNotBlank(workOrderRequest.getIsQualified())) {
				if (OrderAcceptanceEnum.YES.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.ge(WorkOrderDO::getDocumentScore, 80);
				} else if (OrderAcceptanceEnum.NO.name().equals(workOrderRequest.getIsQualified())) {
					wrapper.lt(WorkOrderDO::getDocumentScore, 80);
				}
			}
			if (StringUtils.isNotBlank(workOrderRequest.getAcceptanceType())) {
				wrapper.eq(WorkOrderDO::getAcceptanceType, workOrderRequest.getAcceptanceType());
			}
			wrapper.orderByDesc(WorkOrderDO::getId).orderByDesc(WorkOrderDO::getStoreCode);
		}
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page,wrapper);

		if (CollectionUtils.isEmpty(workOrderDOS.getRecords())) {
			return ResponseUtil.emptyResponse(request, WorkOrderResponse.class, workOrderDOS.getTotal());
		}
		List<WorkOrderDO> workOrderDOList=workOrderDOS.getRecords();
		List<String> storeNoList = workOrderDOList.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList());
		List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(storeNoList);
		Map<String, StoreDetailBO> map = storeDetailBOS.stream().collect(Collectors.toMap(StoreDetailBO::getStoreNo, Function.identity(), (a, b) -> b));

		LambdaQueryWrapper<WorkOrderReceiverDO> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.in(WorkOrderReceiverDO::getWorkOrderNumber, storeNoList);
		List<WorkOrderReceiverDO> orderReceiverDOS = workOrderReceiverBaseService.list(queryWrapper);
		Map<String, List<WorkOrderReceiverDO>> listMap = orderReceiverDOS.stream().collect(Collectors.groupingBy(WorkOrderReceiverDO::getWorkOrderNumber));

		List<WorkOrderResponse> workOrderResponseList = new LinkedList<>();
		for (WorkOrderDO workOrderDO : workOrderDOS.getRecords()) {
			WorkOrderResponse workOrderResponse = new WorkOrderResponse();
			BeanUtils.copyProperties(workOrderDO,workOrderResponse);
			if(workOrderDO.getReceiver()!=null&&workOrderDO.getReceiverMobile()!=null){
				String[] receiver = workOrderDO.getReceiver().split(",");

				String[] receiverMobile = workOrderDO.getReceiverMobile().split(",");
				List<String> encryptPhoneList = new ArrayList<>();
				for (String phone : receiverMobile) {
					String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
					encryptPhoneList.add(phoneNumber);
				}
				receiverMobile = encryptPhoneList.toArray(new String[0]);
				String result = joinStringArrays(receiver, receiverMobile);
				workOrderResponse.setReceiverAndReceiverMobile(result);
			}
			//添加3.0产品售卖情况
			if (MapUtil.isNotEmpty(map) && null != map.get(workOrderDO.getStoreCode())){
				Product3SalesEnum product3SalesEnum = Product3SalesEnum.of(map.get(workOrderDO.getStoreCode()).getProductThridSalesStatus());
				if (Objects.nonNull(product3SalesEnum)) {
					workOrderResponse.setProductThridSalesStatus(product3SalesEnum.getInfo());
				}
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
				workOrderResponse.setIsQualified(Integer.parseInt(workOrderDO.getDocumentScore()) < 80 ? OrderAcceptanceEnum.NO.name() : OrderAcceptanceEnum.YES.name());
			}
			//单个工单对应一个供应商
			if (MapUtil.isNotEmpty(listMap) && CollectionUtils.isNotEmpty(listMap.get(workOrderDO.getWorkOrderNumber()))) {
				WorkOrderReceiverDO workOrderReceiverDO = listMap.get(workOrderDO.getWorkOrderNumber()).stream().findFirst().orElse(null);
				if (Objects.nonNull(workOrderReceiverDO)) {
					workOrderResponse.setSupplierId(workOrderReceiverDO.getSupplierId());
				}
			}
			workOrderResponseList.add(workOrderResponse);
		}
		return ResponseUtil.commonResponse(request, workOrderResponseList, workOrderDOS.getTotal());
	}

	private static String joinStringArrays(String[] name, String[] phone) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < name.length; i++) {
			sb.append(name[i]).append("(").append(phone[i % phone.length]).append("),");
		}
		return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
	}


	public Boolean collate(SettlementCollateRequest request) {
		LambdaQueryWrapper<StoreSettlementDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StoreSettlementDO::getSettlementNo, request.getSettlementNo());
		List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.list(queryWrapper);
		StoreSettlementDO storeSettlementDO = storeSettlementDOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.ORDER_NOT_EXIST));

		if (!SettlementStatusEnum.WAIT_STORE_VERIFY.getType().equals(storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}
		storeSettlementDO.setDocumentStatus(SettlementStatusEnum.WAIT_SUPPLIER_VERIFY.getType());

		//加盟店
		if (Objects.nonNull(request.getStoreTagFlag()) && Objects.nonNull(request.getNeedInvoiceFlag())) {
			NeedInvoiceEnum ifNeedInvoice = NeedInvoiceEnum.NEED;
			//门店标签中不包含：店长持股门店  且 选择 <不需要发票> 选项
			if (Boolean.FALSE.equals(request.getStoreTagFlag()) && Boolean.FALSE.equals(request.getNeedInvoiceFlag())){
				ifNeedInvoice = NeedInvoiceEnum.NOT_NEED;
			}
			storeSettlementDO.setPushInvoiceFlag(ifNeedInvoice.getType());
		}
		storeSettlementMapper.updateById(storeSettlementDO);


        //超过72小时; 则默认供应商确认,流转状态
		try {
			Long expiredDate = System.currentTimeMillis() + (supplierVerifyTimeout * 1000L);
			LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(expiredDate), ZoneId.systemDefault());

			eventThirdService.registerDefaultTimerEvent(storeSettlementDO.getSettlementNo(), null, dateTime, EventTypeEnum.WAIT_SUPPLIER_VERIFY_TIME_OUT);
		} catch (Exception e) {
			log.error("结算单下发注册失败", e);
		}

		return true;
	}


	/**
	 * 支付结算单交付金额的回调接口
	 *
	 * @param httpServletRequest 回调入参
	 * @return 回调出参
	 */
	@ExceptionLarkNotice(bizType = "支付结算单交付金额的回调接口", title = "交付金额的回调接口", urgentType = UrgentTypeEnum.APP_PHONE)
	public String payNoticeCallback(HttpServletRequest httpServletRequest) throws Exception {
		String result = NotifyCommonHandler.notifyHandle(httpServletRequest, publicKey, privateKey);
		log.info("结算支付回调接口返回值：{}", result);
		SendNotifyReq sendNotifyReq = JSON.parseObject(result, SendNotifyReq.class);
		//处理业务逻辑
		if (Objects.nonNull(sendNotifyReq)) {
			//支付成功后修改结算单的支付状态的值为：已完成
			if (PayStatusEnum.S.getType().equals(sendNotifyReq.getResultFlag())) {
				//根据结算单的编号查询，
				LambdaQueryWrapper<StoreSettlementDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(StringUtils.isNotBlank(sendNotifyReq.getOutOrderNo()), StoreSettlementDO::getSettlementNo, sendNotifyReq.getOutOrderNo());
				List<StoreSettlementDO> storeConfigurationDOS = storeSettlementBaseService.list(queryWrapper);
				Optional<StoreSettlementDO> op = storeConfigurationDOS.stream().findFirst();
				if (!op.isPresent()) {
					return NotifyCommonHandler.notifyResultHandle(false, publicKey, privateKey);
				}
				StoreSettlementDO storeConfigurationDO = op.get();

				storeConfigurationDO.setDocumentStatus(SettlementStatusEnum.COMPLETE.getType());
				storeSettlementBaseService.updateById(storeConfigurationDO);
				log.info("结算单：{}的支付状态已修改为已完成。", storeConfigurationDO.getSettlementNo());
				return NotifyCommonHandler.notifyResultHandle(true, publicKey, privateKey);
			}
		}
		return NotifyCommonHandler.notifyResultHandle(false, publicKey, privateKey);
	}

	public static Date getStartOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	public static Date getEndOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}

	/**
	 * 门店结算驳回
	 * @param request
	 * @return
	 */
	public Boolean rejected(SettlementRejectedRequest request) {
		StoreSettlementDO storeSettlementDO = storeSettlementBaseService.querySettlement(request.getSettlementNo());
		if (Objects.isNull(storeSettlementDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		if (!StringUtils.equals(SettlementStatusEnum.WAIT_STORE_VERIFY.getType(), storeSettlementDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}

		SettlementExtJsonBO extJsonBO = new SettlementExtJsonBO();
		if (StringUtils.isNotBlank(storeSettlementDO.getExtra())) {
			extJsonBO = JSON.parseObject(storeSettlementDO.getExtra(), new TypeReference<SettlementExtJsonBO>() {
			});
		}
		extJsonBO.setRejectedReason(request.getRejectedReason());
		extJsonBO.setRejectedAttachment(request.getRejectedAttachment());

		storeSettlementBaseService.update(SettlementStatusEnum.STORE_OBJECTION.getType(), JSON.toJSONString(extJsonBO), storeSettlementDO);

		//飞书通知
		feiShuSendService.storeRejectedMsg(storeSettlementDO);

		return true;
	}

}


















